import { get, post } from './axios'
import type { ApiResponse, PageQuery, PageResult } from '../model/common-model'
import type {
  DeployRecord,
  DeployCreateRequest,
  DeployLogRequest,
  DeployDetail,
  DirectoriesResponse,
  ScanResponse,
  LocalDeployRequest,
  LocalDeployResponse
} from '../model/deploy-model'

/**
 * 获取部署记录列表（分页）
 * @param params 查询参数，支持分页、项目ID、环境和状态筛选
 */
export function getDeployList(params: PageQuery & {
  project_id?: number | string
  environment?: string
  status?: string
}): Promise<ApiResponse<DeployRecord[]>> {
  return get('/deployments/', params)
}

/**
 * 获取项目的部署记录列表（分页）
 * @param projectId 项目ID
 * @param params 查询参数
 */
export function getProjectDeployList(projectId: string | number, params: PageQuery): Promise<ApiResponse<PageResult<DeployRecord>>> {
  return get(`/projects/${projectId}/deployments`, params)
}

/**
 * 获取部署记录详情
 * @param id 部署ID
 */
export function getDeployDetail(id: string | number): Promise<ApiResponse<DeployDetail>> {
  return get(`/deployments/${id}`)
}

/**
 * 创建部署任务
 * @param data 部署参数
 */
export function createDeployment(data: {
  project_version_id: number
  environment: string
  deploy_path?: string
  deployed_by?: string
}): Promise<ApiResponse<DeployDetail>> {
  return post('/deployments/', data)
}

/**
 * 获取部署日志
 * @param request 日志查询参数
 */
export function getDeployLog(request: DeployLogRequest): Promise<ApiResponse<string>> {
  return get(`/deployments/${request.deployId}/logs`, { from: request.from })
}

/**
 * 取消部署
 * @param id 部署ID
 */
export function cancelDeploy(id: string): Promise<ApiResponse<any>> {
  return post(`/deployments/${id}/cancel`)
}

/**
 * 重试部署
 * @param id 部署ID
 */
export function retryDeploy(id: string): Promise<ApiResponse<any>> {
  return post(`/deployments/${id}/retry`)
}

/**
 * 获取部署目录列表
 * @returns 部署目录列表
 */
export function getDeployDirectories(): Promise<ApiResponse<DirectoriesResponse>> {
  return get('/file-scan/directories')
}

/**
 * 扫描目录中的ZIP文件
 * @param directoryId 目录ID
 * @returns 扫描结果
 */
export function scanDirectoryFiles(directoryId: string): Promise<ApiResponse<ScanResponse>> {
  return get(`/file-scan/scan/${directoryId}`)
}

/**
 * 从本地文件部署
 * @param data 部署参数
 * @returns 部署结果
 */
export function deployFromLocalFile(data: LocalDeployRequest): Promise<ApiResponse<LocalDeployResponse>> {
  return post('/file-scan/deploy/local', data)
}
